package com.wisdom.system.api.core.job;

import com.wisdom.system.api.core.factory.BeanFactory;
import com.wisdom.system.entity.job.JobLog;
import com.wisdom.system.entity.sys.SysTableBakJob;
import com.wisdom.system.service.job.JobLogService;
import com.wisdom.system.service.sys.SysTableBakJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 备份数据调度
 */
public class TableBackupJob implements Job {

    SysTableBakJobService sysTableBakJobService = BeanFactory.getBean(SysTableBakJobService.class);

    JobLogService jobLogService = BeanFactory.getBean(JobLogService.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        executeTableBak();
    }

    public void executeTableBak() {
        List<SysTableBakJob> executeList = sysTableBakJobService.getSysTableBakJobExecuteList();
        if (CollectionUtils.isEmpty(executeList)) {
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        executeList.forEach(executeSysTableBakJob -> {
            //执行调度任务前
            int count;
            getJobLog(1, "调度日志:" + "在【" + format + "】执行【" + "从" + executeSysTableBakJob.getTableName() + "备份到" + executeSysTableBakJob.getTableName() + "_bak】的数据备份任务！");
            try {
                count = sysTableBakJobService.executeTableBak(executeSysTableBakJob);
            } catch (Exception e) {
                //异常
                e.printStackTrace();
                getJobLog(2, "调度日志:" + "在【" + format + "】执行【" + "从" + executeSysTableBakJob.getTableName() + "备份到" + executeSysTableBakJob.getTableName() + "_bak】的数据备份任务," + e.getMessage());
                return;
            }
            //执行表备份任务完成
            getJobLog(2, "调度日志:" + "在【" + format + "】执行【" + "从" + executeSysTableBakJob.getTableName() + "备份到" + executeSysTableBakJob.getTableName() + "共" + count + "条" + "】的数据备份任务完成！");
        });
    }

    /**
     * 执行日志保存
     *
     * @param state
     * @param content
     * @return
     */
    private JobLog getJobLog(Integer state, String content) {
        JobLog jobLog = new JobLog();
        jobLog.setFkJobLogCode("01");
        jobLog.setState(state);
        jobLog.setContent(content);
        jobLogService.addJobLogInfo(jobLog);
        return jobLog;
    }

}
